package com.company.project.service.impl;

import com.alipay.api.AlipayApiException;
import com.company.project.core.Result;
import com.company.project.core.ResultGenerator;
import com.company.project.dao.*;
import com.company.project.model.*;
import com.company.project.model.request.QueryParams;
import com.company.project.model.response.OrderItem;
import com.company.project.model.response.OrderResponse;
import com.company.project.model.response.PageList;
import com.company.project.service.OrderMainService;
import com.company.project.core.AbstractService;
import com.company.project.utils.ImageBinary;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by CodeGenerator on 2020/04/21.
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OrderMainServiceImpl extends AbstractService<OrderMain> implements OrderMainService {
    @Resource
    private OrderMainMapper orderMainMapper;
    @Resource
    private ShopInfoMapper shopInfoMapper;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private FoodMapper foodMapper;
    @Resource
    private AdminUserMapper userMapper;
    @Autowired
    private OrderCommentMapper commentMapper;

    @Override
    public Result generateOrder(OrderMain orderMain) {
        ShopInfo query = new ShopInfo();
        List<Food> list = orderMain.getFoodList();
        // 获取购物车商品的店铺ids
        List<Integer> shopIds = new ArrayList<>();
        for(Food food : list) {
            Integer shopId = food.getShopId();
            if(!shopIds.contains(shopId)) {
                shopIds.add(shopId);
            }
        }

        for(Integer shopId : shopIds) {
            query.setShopId(shopId);
            ShopInfo shop = shopInfoMapper.selectOne(query);
            if(shop == null) {
                return ResultGenerator.genFailResult("查不到商店");
            }
            OrderMain entity = new OrderMain();
            entity.setUserId(orderMain.getUser().getUserId());
            entity.setShopId(shop.getShopId());
            entity.setShopName(shop.getShopName());
            entity.setStatus(1);
            entity.setCreatTime(new Timestamp(System.currentTimeMillis()));
            entity.setBoxCost(shop.getBoxCost());
            entity.setSendCost(shop.getSendCost());
            BigDecimal total = new BigDecimal(0);
            List<Food> foodList = orderMain.getFoodList();
            for(Food food : foodList) {
                if(food.getShopId().equals(shopId)) {
                    total = total.add(food.getSellPrice());
                }
            }
            entity.setTotalMoney(shop.getBoxCost().add(shop.getSendCost()).add(total));

            //拼接foodId字符串
            StringBuilder ids = new StringBuilder();
            for(int i = 0; i < foodList.size(); i++) {
                if(foodList.get(i).getShopId().equals(shopId)) {
                    if(i == foodList.size() - 1) {
                        ids.append(foodList.get(i).getFoodId().toString()).append(":").append(foodList.get(i).getAmount().toString());
                    } else {
                        ids.append(foodList.get(i).getFoodId().toString()).append(":").append(foodList.get(i).getAmount().toString()).append(",");
                    }
                }
            }
            entity.setFoodids(ids.toString());
            orderMainMapper.insert(entity);
        }
        // 将购物车内的商品信息删除
        redisTemplate.opsForList().leftPop(orderMain.getUser().getUserId().toString());
        return ResultGenerator.genSuccessResult();
    }


    @Override
    public Result getOrderByUserId(Integer userId) {
        Condition condition = new Condition(OrderMain.class);
        condition.createCriteria().andEqualTo("userId", userId);
        List<OrderMain> list = orderMainMapper.selectByCondition(condition);

        List<OrderItem> orderList = new ArrayList<>();
        // 获取订单信息
        for(OrderMain order : list) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getOrderId());
            StringBuilder foodInfo = new StringBuilder();
            String[] foodids = order.getFoodids().split(",");
            List<Integer> foodIdList = new ArrayList<>();
            for (String foodid : foodids) {
                String[] foodIdAndNum = foodid.split(":");
                Food query = new Food();
                query.setFoodId(Integer.parseInt(foodIdAndNum[0]));
                Food food = foodMapper.selectOne(query);
                foodIdList.add(food.getFoodId());
                foodInfo.append(food.getName()).append("x").append(Integer.parseInt(foodIdAndNum[1])).append(" ");
            }
            ShopInfo query = new ShopInfo();
            query.setShopId(order.getShopId());
            ShopInfo shopInfo = shopInfoMapper.selectOne(query);

            orderItem.setFoodIds(foodIdList);
            orderItem.setShopInfo(shopInfo);
            orderItem.setFoodInfo(foodInfo.toString());
            orderItem.setStatus(order.getStatus());
            orderItem.setTotal(order.getTotalMoney());
            orderList.add(orderItem);
        }
        return ResultGenerator.genSuccessResult(orderList);
    }

    @Override
    public Result checkPay(OrderMain orderMain) {
        User query = new User();
        query.setUserId(orderMain.getUserId());
        User user = userMapper.selectOne(query);
        if (StringUtils.isBlank(user.getTelephone()) || StringUtils.isBlank(user.getAddress())) {
           return ResultGenerator.genFailResult("请先填写配送地址和手机号");
        }
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public Result receive(Integer orderId) {
        OrderMain query = new OrderMain();
        query.setOrderId(orderId);
        OrderMain entity = orderMainMapper.selectOne(query);
        entity.setStatus(3);
        orderMainMapper.updateByPrimaryKey(entity);
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public Result comment(OrderComment comment) {
        comment.setCreatTime(new Timestamp(System.currentTimeMillis()));
        String projectPath = System.getProperty("user.dir");
        if(StringUtils.isNotBlank(comment.getImg())) {
            String filePath = projectPath + "\\src\\main\\resources\\static\\" + comment.getImg();
            String imgs = ImageBinary.getImageBinary(filePath);
            comment.setImgs(imgs);
        }
        List<Integer> foodIds = comment.getFoodIds();
        for(Integer foodId : foodIds) {
            OrderComment insert = new OrderComment();
            BeanUtils.copyProperties(comment, insert);
            insert.setFoodId(foodId);
            commentMapper.insert(insert);
        }
        OrderMain query = new OrderMain();
        query.setOrderId(comment.getOrderId());
        OrderMain entity = orderMainMapper.selectOne(query);
        entity.setStatus(4);
        orderMainMapper.updateByPrimaryKey(entity);
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public void finish(Integer orderId) {
        OrderMain entity = new OrderMain();
        entity.setOrderId(orderId);
        OrderMain query = orderMainMapper.selectOne(entity);
        BeanUtils.copyProperties(query, entity);
        entity.setStatus(2);
        orderMainMapper.updateByPrimaryKey(entity);
    }

    @Override
    public Result num(Integer id) {
        OrderMain query = new OrderMain();
        if(id != null && id != 0) {
            query.setShopId(id);
        }
        List<Integer> list = new ArrayList<>();
        int all = orderMainMapper.selectCount(query);
        query.setStatus(1);
        int pay = orderMainMapper.selectCount(query);
        query.setStatus(2);
        int sh = orderMainMapper.selectCount(query);
        query.setStatus(3);
        int comment = orderMainMapper.selectCount(query);
        query.setStatus(4);
        int finish = orderMainMapper.selectCount(query);
        list.add(all);
        list.add(pay);
        list.add(sh);
        list.add(comment);
        list.add(finish);
        return ResultGenerator.genSuccessResult(list);
    }

    @Override
    public Result list(QueryParams queryParams) {
        int page = queryParams.getPage();
        int size = queryParams.getSize();
        if (queryParams.getTime() != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            queryParams.setTimeString(dateFormat.format(queryParams.getTime()));
        }
        queryParams.setStart((page - 1) * size);
        List<OrderMain> list = orderMainMapper.getOrderList(queryParams);
        Integer total = orderMainMapper.getOrderListTotal(queryParams);
        PageList<OrderMain> pageList = new PageList<>();
        pageList.setList(list);
        pageList.setTotal(total);
        return ResultGenerator.genSuccessResult(pageList);
    }

    @Override
    public Result detail(Integer orderId) {
        OrderMain query = new OrderMain();
        query.setOrderId(orderId);
        OrderMain orderMain = orderMainMapper.selectOne(query);
        OrderResponse response = new OrderResponse();
        response.setBoxCost(orderMain.getBoxCost());
        response.setSendCost(orderMain.getSendCost());
        String[] foodids = orderMain.getFoodids().split(",");
        BigDecimal foodTotal = new BigDecimal(0);
        List<Food> foodList = new ArrayList<>();
        for (String foodid : foodids) {
            String[] foodIdAndNum = foodid.split(":");
            Food q = new Food();
            q.setFoodId(Integer.parseInt(foodIdAndNum[0]));
            Food food = foodMapper.selectOne(q);
            food.setAmount(Integer.parseInt(foodIdAndNum[1]));
            foodTotal = foodTotal.add(food.getSellPrice());
            foodList.add(food);
        }
        response.setFoodTotal(foodTotal);
        response.setFoodList(foodList);
        return ResultGenerator.genSuccessResult(response);
    }

    @Override
    public List<OrderMain> getList(Integer shopId) {
        return orderMainMapper.getList(shopId);
    }
}
